package com.ddxz.demo.quartz.task;

import com.ddxz.demo.quartz.entity.GroupEntity;
import com.ddxz.demo.quartz.mapper.TaskMapper;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.session.SqlSession;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/11/24
 */

@Configuration
public class DdxzQuartzListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onApplicationEvent(ContextRefreshedEvent applicationReadyEvent) {
        // 当前使用sqlite，不支持游标
//        try(Cursor<GroupEntity> cursor = session.selectCursor(TaskMapper.class.getName() + ".getAllRunningTask")) {
//            cursor.forEach(entity -> manager.startJob(entity));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        List<GroupEntity> entityList = mapper.getRunningTask();
        entityList.forEach(entity -> manager.startJob(entity));
    }

    private SqlSession session;

    private DdxzJobManager manager;

    private TaskMapper mapper;

    public DdxzQuartzListener(SqlSession session, DdxzJobManager manager, TaskMapper mapper) {
        this.session = session;
        this.manager = manager;
        this.mapper = mapper;
    }
}
